﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using MesDock.Entity;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.IO.Ports;
using Time.OPCServerV;
using Time.IBLL;
using Time.BLL;
using Time.DB;
using System.Timers;
using System.Configuration;
using Time.Foramework;

namespace MesDock
{
    public partial class MainForm : Form
    {
        //plc操作对象
        private OpcBusiness opc;
        //用于接收小车流水号
        object plcCarNo = null;

        //声明委托
        private delegate void ConsignMethod(string method, string timeS, string timeNow);
        private delegate void MesResult(object c);
        private delegate void MesCheckResult(string message, string type, DataTable dataTable);
        //实验单号
        private string testNo = "";
        //工号
        private string UserID = "JS000079";
        //授权码
        private string AccessToken = "";
        //设备编号
        private string EquipmentID = "";
        //mes服务器状态
        private bool IfOnLine = true;
        //来料校验状态
        private bool IfCheck = true;

        private DeviceData deviceData = new DeviceData();
        private int staCycle = 0;

        private string[] stations = { "预热过渡段", "预热段1工位", "预热段2工位", "真空过渡段", "真空1段1工位", "真空1段2工位", "真空2段1工位", "真空2段2工位",
        "真空3段1工位", "真空3段2工位", "真空4段1工位", "真空4段2工位", "真空5段1工位", "真空5段2工位", "真空6段1工位", "真空6段2工位", "冷却过渡段", "冷却段" };
        private static string ChanneOtherDevice = ConfigurationManager.AppSettings["ChanneOtherDevice"].ToString();


        private List<string> TableNames = new List<string>();

        //转移映射配置信息
        int IsAuto = 0;
        int MapCount = 0;
        string SourceTableStr;
        string[] SourceTableArr;
        string[] MapSourceTableStr;
        string[] MapSourceFieldStr;
        string[] MapDestTableStr;
        string[] MapDestFieldStr;
        public static string configPath;
        bool OpcConnectBl = false;
        private Thread thdAutoMove;//= new Thread(new ThreadStart(AutoMove));
        DataTable objDt = new DataTable();
        IEqAlarm_BLL objIEqAlarm_BLL = new EqAlarm_BLL();
        public MainForm()
        {
            InitializeComponent();
        }

        #region 窗体加载
        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                //string SmallCarNo = "";
                //int AscciiData = Convert.ToInt32(Convert.ToInt32(12592) % 256);
                //SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                //AscciiData = Convert.ToInt32(Convert.ToInt32(12592) / 256);
                //SmallCarNo += ASCIIConvertString.Chr(AscciiData);


                //获取配置信息
                getMoveMapConfig();
                //记录登录时间
                this.toolStripStatusLabel2.Text = "登录时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //配置文件地址
                configPath = Application.StartupPath + "\\Config.ini";
                List<string> lstItem = new List<string>();

                DataTable objDt = objIEqAlarm_BLL.getDataTable("HK_EqStationCode");

                for (int i = 0; i < objDt.Rows.Count; i++)
                {
                    cboStation.Items.Add(objDt.Rows[i][1].ToString() + "_" + objDt.Rows[i][2].ToString());
                    for (int c = 2; c < objDt.Columns.Count; c++)
                    {
                        if (!string.IsNullOrEmpty(objDt.Rows[i][c].ToString()) && objDt.Rows[i][c].ToString().Length > 3)
                        {
                            if (c == 2)
                            {
                                string smallCartStr = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);
                                for (int k = 0; k < 10; k++)
                                {
                                    string smallCartStrAddress = smallCartStr + k.ToString();
                                    lstItem.Add(ChanneOtherDevice + smallCartStrAddress);
                                }
                            }
                            else if (c == 8)
                            {
                                string smallCartStr = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);
                                for (int n = 0; n < 4; n++)
                                {
                                    string smallCartStrAddress = smallCartStr + n.ToString();
                                    lstItem.Add(ChanneOtherDevice + smallCartStrAddress);
                                }
                            }
                            else
                            {
                                lstItem.Add(ChanneOtherDevice + objDt.Rows[i][c].ToString());
                            }
                        }
                    }
                }
                objDt = objIEqAlarm_BLL.getDataTable("t_KepServerConfig");
                for (int i = 0; i < objDt.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty(objDt.Rows[i]["Name"].ToString()))
                    {
                        lstItem.Add(ChanneOtherDevice + objDt.Rows[i]["Name"].ToString());
                    }
                }

                //连接OPCServer并初始化OPC连接
                opc = OpcBusiness.GetInstance();

                string errorStr = null;
                OpcConnectBl = opc.Init(lstItem, ref errorStr);
                if (!OpcConnectBl)
                {
                    this.Invoke(new MesResult(ShowMessageForm), errorStr);
                    this.tbMessage.Text = errorStr;
                    return;
                }

                //默认登录工号
                this.tbShowUser.Text = "JS000079";
                this.tbShowUser.BackColor = Color.LightGreen;

                //默认开启来料校验
                this.cbOn.Checked = true;

                //离线状态的相关设置                              -
                this.tbMesStatus.Text = "离线";
                this.tbMesStatus.BackColor = Color.Red;

                this.textBox1.Hide();
                this.button1.Hide();
                this.label1.Hide();
                this.button2.Hide();


                //开启timer，默认60秒运行一次
                this.timerProduct.Enabled = true;
                this.timerProduct.Interval = 1000 * 10;

                //显示系统当前时间
                System.Timers.Timer timerStatus = new System.Timers.Timer();
                timerStatus.Elapsed += new System.Timers.ElapsedEventHandler(timerStatus_Tick);
                timerStatus.Interval = 10000;
                timerStatus.Enabled = true;


                //设置串口参数
                string[] str = SerialPort.GetPortNames();
                foreach (var item in str)
                {
                    comList.Items.Add(item);
                }
                if (comList.Items.Count > 0)
                {
                    comList.SelectedIndex = 0;
                }
                DisplayStatus();

            }
            catch (Exception ef)
            {
                this.tbMessage.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\nPLC地址初始化时发生错误！";

                PrintLog(ef.Message);
            }
            try
            {
                //打开扫码枪串口
                OpenSerialPort();
                //扫码枪串口绑定响应事件
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);

                string filePath = Application.StartupPath + "\\Config.ini";

                this.tbShowTestNo.Text = ConfigOperate.ReadIniKeys("CONFIG", "testNo", filePath);
                this.tbServerAddress.Text = ConfigOperate.ReadIniKeys("CONFIG", "ServerAddress", configPath);
                this.tbAccessToken.Text = ConfigOperate.ReadIniKeys("CONFIG", "AccessToken", configPath);
                this.tbEquipmentID.Text = ConfigOperate.ReadIniKeys("CONFIG", "EquipmentID", configPath);
                this.comList.Text = ConfigOperate.ReadIniKeys("SerialPort", "PortName", configPath);
                this.txtBatLength.Text = ConfigOperate.ReadIniKeys("BatCif", "BatLength", configPath);
                //授权码
                AccessToken = this.tbAccessToken.Text.Trim();
                //设备编号
                EquipmentID = this.tbEquipmentID.Text.Trim();
                //窗口默认大小
                this.WindowState = FormWindowState.Normal;

                //连接MES服务器
                Application.DoEvents();
                tbMessage.Text = "正在连接MES服务器...";
                this.cbOnLine.Checked = true;

                OpenThread("mesStatus");

                /////test代码
                //// SubmitProduct(DateTime.Now.AddDays(-60).ToString (), DateTime.Now.ToString ());
                //读取小车流水号
                OpenThread("readCarNo");


            }
            catch (Exception ex)
            {
                this.tbMessage.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n连接服务器时发生错误！";
                PrintLog(ex.Message.ToString());
            }
            try
            {
                Thread objSpTh = new Thread(new ThreadStart(UpDataPLCData));
                objSpTh.IsBackground = true;
                objSpTh.Start();
                Thread objStTh = new Thread(new ThreadStart(UpStationDataPLCData));
                objStTh.IsBackground = true;
                objStTh.Start();
                DataTable objTempDt = new DataTable();
                objTempDt = objIEqAlarm_BLL.getData("select tn.工位,Convert(decimal(18,2),tn.温度SV) as 温度SV,Convert(decimal(18,2),tn.温度测量值PV1) as 温度测量值PV1,Convert(decimal(18,2),tn.温度测量值PV2) as 温度测量值PV2,tn.真空度高限SV,tn.真空度低限SV,tn.真空度PV,tn.采集时间, tn.小车流水号" +
                                                    " from HK_EqTechnologyParameterInfo tn left join dbo.HK_EqStationCode tc on tn.工位 = tc.工位 " +
                                                    " where tn.采集时间 in(select MAX(t1.采集时间) from HK_EqTechnologyParameterInfo t1 group by t1.工位) order by tc.Item asc");

                ProcessDataGridView.DataSource = objTempDt.DefaultView;
            }
            catch (Exception fef)
            {
                tbMessage.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "获取PLC数据错误！！！";
                PrintLog(fef.Message.ToString());
            }
        }
        /// <summary>
        /// 当前工位状态
        /// </summary>
        private void DisplayStatus()
        {
            try
            {

                dgvStatus.DataSource = null;
                dgvStatus.DataSource = objIEqAlarm_BLL.getData("select tc.item as 序列,tn.工位,tn.小车流水号,  tn.采集时间 from HK_EqStationInfo tn left join dbo.HK_EqStationCode tc on tn.工位 = tc.工位 where tn.采集时间 in(select MAX(t1.采集时间) from HK_EqStationInfo t1 group by t1.工位) order by tc.Item asc");
                dgvStatus.Columns[0].Width = 65;
                dgvStatus.Columns[1].Width = 230;
                dgvStatus.Columns[2].Width = 230;
                dgvStatus.Columns[3].Width = 200;
                dgvStatus.Refresh();
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 读取PLC对应工位数据更新到数据库
        /// </summary>
        private void UpDataPLCData()
        {
            string tableName = null;
            while (true)
            {
                string tempStrSql = null;
                DataTable objDt = objIEqAlarm_BLL.getDataTable("HK_EqStationCode");

                for (int i = 0; i < objDt.Rows.Count; i++)
                {
                    BK:
                    if (i >= objDt.Rows.Count)
                    {
                        break;
                    }
                    DataTable objTempDt = new DataTable();

                    tableName = "HK_EqTechnologyParameterInfo";
                    tempStrSql = string.Format("select * from HK_EqTechnologyParameterInfo where 工位 = '{0}'  and  采集时间 between '{1}' and '{2}'", tableName, objDt.Rows[i]["工位"].ToString().Trim(), DateTime.Now.AddMinutes(-1), DateTime.Now);


                    objTempDt = objIEqAlarm_BLL.getData(tempStrSql);
                    if (objTempDt.Rows.Count < 1)
                    {

                        tempStrSql = "insert into HK_EqTechnologyParameterInfo (工位,小车流水号 ,温度SV,温度测量值PV1,温度测量值PV2,真空度低限SV,真空度高限SV ,真空度PV,采集时间)values(";

                        tempStrSql += "'" + objDt.Rows[i][1].ToString() + "'";
                        for (int c = 2; c < objDt.Columns.Count; c++)
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(objDt.Rows[i][c].ToString().Trim()))
                                {
                                    string aaa = objDt.Rows[i][c].ToString();
                                    string SmallCarNo = null;
                                    var receiveData = opc.ReadData(ChanneOtherDevice + objDt.Rows[i][c].ToString());
                                    if (c == 2)
                                    {
                                        string ReadPLCSmallCard = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);

                                        for (int k = 0; k < 10; k++)
                                        {
                                            string PLCAddress = ReadPLCSmallCard;
                                            PLCAddress += k.ToString();
                                            var receiveDataSM = opc.ReadData(ChanneOtherDevice + PLCAddress);
                                            try
                                            {
                                                int AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) % 256);
                                                SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                                                AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) / 256);
                                                SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                                            }
                                            catch (Exception exs)
                                            {
                                                tbMessage.Text = "取PLC数据失败，详细参考日志。";
                                                PrintLog(tbMessage.Text);
                                            }
                                        }
                                        SmallCarNo = SmallCarNo.Replace("\0", "");
                                        if (SmallCarNo.Trim().Length != 20)
                                        {
                                            SmallCarNo = "";
                                        }
                                        if (string.IsNullOrEmpty(SmallCarNo))
                                        {
                                            i++;
                                            goto BK;
                                        }
                                        tempStrSql += string.Format(",'{0}'", SmallCarNo);
                                    }
                                    else if (c > 2 && c < 6)
                                    {
                                        double rd = Convert.ToInt32(receiveData) * 0.1;
                                        rd = Math.Round(rd, 2);
                                        tempStrSql += string.Format(",'{0}'", rd.ToString());

                                    }
                                    else if (c == 8)
                                    {
                                        //获取真空PV的地址码前五位  如 D12100 取前五位 D1210
                                        string ReadPLCSmallCard = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);
                                        //用于存放真空度4个寄存器数据
                                        double plcPlusValue = 0;
                                        for (int m = 0; m < 4; m++)
                                        {
                                            //生成相邻的四个地址码
                                            string PLCAddress = ReadPLCSmallCard;
                                            PLCAddress += m.ToString();
                                            try
                                            {
                                                //读取PLC数据
                                                var receiveDataSM = opc.ReadData(ChanneOtherDevice + PLCAddress);
                                                //获取的数据相加
                                                double tempPlcValue = Convert.ToDouble(receiveDataSM);
                                                plcPlusValue += Math.Round(tempPlcValue, 2);
                                            }
                                            catch (Exception exs)
                                            {
                                                tbMessage.Text = "取PLC真空PV数据失败，详细参考日志。";
                                                PrintLog(tbMessage.Text);
                                            }
                                        }
                                        tempStrSql += string.Format(",'{0}'", Convert.ToString(plcPlusValue));
                                    }

                                    else
                                    {
                                        tempStrSql += string.Format(",'{0}'", Convert.ToString(receiveData));
                                    }

                                }
                                else
                                {
                                    tempStrSql += ",'0'";
                                }
                            }
                            catch (Exception es)
                            {
                                tempStrSql += ",'0'";
                            }
                        }
                        tempStrSql += string.Format(",'{0}')", DateTime.Now.ToString());
                    }
                    else
                    {
                        i++;
                        goto BK;
                    }

                    int result = objIEqAlarm_BLL.ExecuteNonQuery(tempStrSql, null);
                }
                Thread.Sleep(20000);
            }

        }

        /// <summary>
        /// 读取PLC对应工位数据更新到数据库
        /// </summary>
        private void UpStationDataPLCData()
        {
            while (true)
            {

                DataTable objDt = objIEqAlarm_BLL.getDataTable("HK_EqStationCode");
                string tempStrSql = null;
                for (int i = 0; i < objDt.Rows.Count; i++)
                {

                    returnStation:
                    if (i >= objDt.Rows.Count)
                    {
                        break;
                    }

                    DataTable objTempDt = new DataTable();
                    //tempStrSql = string.Format("select * from HK_EqStationInfo where 工位 = '{0}' order by  采集时间 desc ", objDt.Rows[i]["工位"].ToString().Trim());
                    //objTempDt = objIEqAlarm_BLL.getData(tempStrSql);
                    tempStrSql = "insert into HK_EqStationInfo (工位,小车流水号 ,温度SV,温度测量值PV1,温度测量值PV2,真空度低限SV,真空度高限SV ,真空度PV,采集时间)values(";

                    tempStrSql += "'" + objDt.Rows[i]["工位"].ToString() + "'";
                    for (int c = 2; c < objDt.Columns.Count; c++)
                    {
                        try
                        {

                            if (!string.IsNullOrEmpty(objDt.Rows[i][c].ToString()))
                            {
                                string aaa = objDt.Rows[i][c].ToString();
                                var receiveData = opc.ReadData(ChanneOtherDevice + objDt.Rows[i][c].ToString());
                                if (c == 2)
                                {
                                    string SmallCarNo = null;
                                    string ReadPLCSmallCard = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);

                                    for (int k = 0; k < 10; k++)
                                    {
                                        string PLCAddress = ReadPLCSmallCard;
                                        PLCAddress += k.ToString();
                                        var receiveDataSM = opc.ReadData(ChanneOtherDevice + PLCAddress);
                                        try
                                        {
                                            int AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) % 256);
                                            SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                                            AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) / 256);
                                            SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                                        }
                                        catch (Exception exs)
                                        {
                                            tbMessage.Text = "取PLC数据失败，详细参考日志。";
                                            PrintLog(tbMessage.Text);
                                        }
                                    }
                                    SmallCarNo = SmallCarNo.Replace("\0", "");
                                    if (SmallCarNo.Trim().Length != 20)
                                    {
                                        SmallCarNo = "";
                                    }
                                    if (string.IsNullOrEmpty(SmallCarNo))
                                    {
                                        break;
                                    }

                                    string searchStrSql = string.Format("select * from HK_EqStationInfo where 工位 = '{0}' and 小车流水号 = '{1}'", objDt.Rows[i]["工位"].ToString(), SmallCarNo);

                                    objTempDt = objIEqAlarm_BLL.getData(searchStrSql);
                                    //PrintInsertLog(tempStrSql);
                                    if (objTempDt.Rows.Count > 0)
                                    {
                                        i++;
                                        goto returnStation;
                                    }

                                    tempStrSql += string.Format(",'{0}'", SmallCarNo);
                                }
                                else if (objDt.Columns[c].ColumnName.Contains("真空度PV") || c==8)
                                {
                                    string ReadPLCPVAddress = objDt.Rows[i][c].ToString().Substring(0, objDt.Rows[i][c].ToString().Length - 1);

                                    double tempValues = 0;
                                    for (int n = 0; n<4;n++)
                                    {
                                        string PLCPVAddress = ReadPLCPVAddress;
                                        PLCPVAddress += n.ToString();
                                        var receiveDataSM = opc.ReadData(ChanneOtherDevice + PLCPVAddress); 
                                        double rd = Convert.ToDouble(receiveDataSM) ; 
                                        tempValues += Math.Round(rd,2);
                                    }
                                    tempStrSql += string.Format(",'{0}'", tempValues.ToString ());
                                }
                                else
                                {
                                    tempStrSql += string.Format(",'{0}'", Convert.ToString(receiveData));
                                }

                            }

                            else
                            {
                                tempStrSql += ",'0'";
                            }
                        }
                        catch (Exception es)
                        {
                            tempStrSql += ",'0'";
                        }
                    }
                    tempStrSql += string.Format(",'{0}')", DateTime.Now.ToString());
                    int result = objIEqAlarm_BLL.ExecuteNonQuery(tempStrSql, null);
                }
                Thread.Sleep(20000);
            }
        }

        public int getMoveMapConfig()
        {
            int rtn = 0;
            string INIFilePath = System.Environment.CurrentDirectory + @"\MoveMapConfig.ini";
            try
            {
                IsAuto = int.Parse(ConfigOperate.ReadIniKeys("CommonConfig", "IsAuto", INIFilePath));
                MapCount = int.Parse(ConfigOperate.ReadIniKeys("MapCount", "Count", INIFilePath));
                SourceTableStr = ConfigOperate.ReadIniKeys("SourceTable", "NameStr", INIFilePath);
                SourceTableArr = SourceTableStr.Split(',');
                MapSourceTableStr = new string[MapCount];
                MapSourceFieldStr = new string[MapCount];
                MapDestTableStr = new string[MapCount];
                MapDestFieldStr = new string[MapCount];
                for (int i = 0; i < MapCount; i++)
                {
                    MapSourceTableStr[i] = ConfigOperate.ReadIniKeys("Map" + (i + 1), "SourceTable", INIFilePath);
                    MapSourceFieldStr[i] = ConfigOperate.ReadIniKeys("Map" + (i + 1), "SourceField", INIFilePath);
                    MapDestTableStr[i] = ConfigOperate.ReadIniKeys("Map" + (i + 1), "DestTable", INIFilePath);
                    MapDestFieldStr[i] = ConfigOperate.ReadIniKeys("Map" + (i + 1), "DestField", INIFilePath);
                }
                rtn = 1;
            }
            catch (SystemException ex)
            {
                rtn = 0;
            }
            return rtn;
        }
        private void timerStatus_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel3.Text = "系统当前时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 打开串口
        /// <summary>
        /// 打开串口按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenSerialPort();
        }
        /// <summary>
        /// 打开串口，根据配置文件设置的属性打开串口
        /// </summary>
        private void OpenSerialPort()
        {
            serialPort = new SerialPort();

            if (serialPort.IsOpen == false)
            {
                string filePath = Application.StartupPath + "\\Config.ini";

                serialPort.PortName = ConfigOperate.ReadIniKeys("SerialPort", "PortName", filePath);
                //波特率
                serialPort.BaudRate = Convert.ToInt32(ConfigOperate.ReadIniKeys("SerialPort", "BaudRate", filePath));
                ////数据位
                serialPort.DataBits = Convert.ToInt32(ConfigOperate.ReadIniKeys("SerialPort", "DataBits", filePath));
                ////停止位
                serialPort.StopBits = (StopBits)Convert.ToInt32(ConfigOperate.ReadIniKeys("SerialPort", "StopBits", filePath));
                ////无奇偶校验位
                serialPort.Parity = Parity.None;
                ////读写超时时间
                serialPort.ReadTimeout = 200;
                serialPort.WriteTimeout = -1;
                //serialPort.BaudRate = 9600;
                //serialPort.DataBits = 8;
                //serialPort.StopBits = StopBits.One;
                //serialPort.Parity = Parity.None;

                try
                {
                    serialPort.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnOpen.Text = "关闭串口";
                this.lbSerialStatus.Text = "串口已打开！";
            }
            else
            {
                try
                {
                    serialPort.Close();
                    button1.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnOpen.Text = "打开串口";
                lbSerialStatus.Text = "串口已关闭！";
            }
        }
        #endregion

        #region 接收扫码枪数据
        //扫码时间
        private string scanTime;
        //扫码结果
        private bool scanResult;
        //用于传递扫码状态
        object scanStatus;
        //plc对象默认值
        int iErr = -1;
        /// <summary>
        /// 接收扫码枪数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] reData = new byte[serialPort.BytesToRead];
            serialPort.Read(reData, 0, reData.Length);
            this.AddData(reData);
        }
        /// <summary>
        /// 改变格式
        /// </summary>
        /// <param name="data"></param>
        private void AddData(byte[] data)
        {
            try
            {
                CheckData(new ASCIIEncoding().GetString(data));
            }
            catch (Exception ex)
            {
                tbMessage.AppendText(ex.ToString());
            }
        }
        /// <summary>
        /// 校验电池二维码
        /// </summary>
        /// <param name="data"></param>
        private void CheckData(string cellCode)
        {
            //读取小车流水号
            if (plcCarNo == null)
            {
                ReadPlc();
            }
            int BatLength = 24;
            try
            {
                BatLength = Convert.ToInt32(txtBatLength.Text.Trim());
            }
            catch (Exception ess)
            {
                this.Invoke(new MesResult(ShowMessageForm), "电池码长度未设置！");
            }

            //防止扫码枪将多个条码拼接到一起，条码固定长度24
            if (cellCode.Length != BatLength)
            {
                tbMessage.Text = cellCode;
                this.Invoke(new MesResult(ShowMessageForm), "扫码失败！");

                //通知plc电池扫码失败
                scanStatus = "3";
                Thread.Sleep(200);
                opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                Thread.Sleep(200);
                return;
            }
            this.Invoke(new MethodInvoker(delegate { this.tbInputNo.Text = cellCode; }));
            //电池扫码失败
            if (cellCode.ToUpper().Contains("ERROR"))
            {
                this.Invoke(new MesResult(ShowMessageForm), "扫码失败！");

                //通知plc电池扫码失败
                scanStatus = "3";
                Thread.Sleep(200);
                opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                Thread.Sleep(200);

                return;
            }

            //查询电池是否已经保存
            DataTable table = new DataBaseOperate().loadDate("select * from HK_EqProductInfo where 电池二维码='" + cellCode + "'");
            if (table.Rows.Count != 0)
            {
                new DataBaseOperate().loadDate(string.Format("insert into RPT_Scan (cellCode,addDate)values('{0}','{1}')", cellCode,
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                //tbMessage.Text = "电池" + data + "在以下时间：" + table.Rows[0]["扫码时间"] + " 已经扫码!系统不会重复添加！";
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] {"电池" + cellCode + "在以下时间：" + table.Rows[0]["扫码时间"] +
                    " 已经扫码!系统不会重复添加！" ,null,null});

                this.Invoke(new MesResult(ShowMessageForm), "电池 " + cellCode + " 重复扫码！");

                //通知plc扫下一个电池
                scanStatus = "1";
                Thread.Sleep(200);
                opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                Thread.Sleep(200);
                return;
            }

            //扫码时间
            scanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //封装json数据
            JArray jArray = new JArray();

            jArray.Add(cellCode);
            JObject jObject = new JObject();
            jObject.Add("sn", jArray);
            jObject.Add("test", false);
            //来料校验,默认为true
            scanResult = true;
            if (this.IfCheck)
            {
                if (this.IfOnLine)
                {
                    scanResult = SubmitToMesTest("verify", jObject.ToString(), null);
                }
            }

            if (scanResult)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    try
                    {
                        //表单满719行清空（最后一行为空），重新添加记录
                        if (inputDataGridView.RowCount == 719)
                        {
                            inputDataGridView.Rows.Clear();
                        }
                        //表单添加一行记录
                        inputDataGridView.Rows.Add(cellCode, scanTime);
                        //清除第一行的选中状态
                        inputDataGridView.Rows[0].Selected = false;
                        //滚动显示最后一行
                        inputDataGridView.FirstDisplayedScrollingRowIndex = inputDataGridView.RowCount - 1;
                        //保存数据
                        string sql = "insert into HK_EqProductInfo (电池二维码,扫码时间,设备编号,电池代码,小车流水号,测试结果) " + "values('"
                            + cellCode + "','" + scanTime + "','" + this.tbEquipmentID.Text.ToString() + "','" + (inputDataGridView.RowCount - 1)
                            + "','','合格')";
                        //+"','" + this.tbInputCarNo.Text.Trim() + "','合格')";
                        new DataBaseOperate().loadDate(sql);

                        //通知plc电池校验合格
                        scanStatus = "1";
                        Thread.Sleep(200);
                        opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                        Thread.Sleep(200);
                    }
                    catch (Exception ex)
                    {
                        //通知plc电池入库失败
                        scanStatus = "2";
                        Thread.Sleep(200);
                        opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                        PrintLog(ex.ToString());
                        this.tbMessage.Text = ex.ToString();
                    }
                }));
            }
            else
            {
                this.Invoke(new MesResult(ShowMessageForm), "电池 " + cellCode + " 未通过校验！");
                //通知plc电池校验不合格
                scanStatus = "2";

                Thread.Sleep(200);
                opc.WriteData("D11424", scanStatus, ref iErr, "Channel1.", "Device2.");
                Thread.Sleep(200);
            }
            return;
        }

        private void ShowMessageForm(object message)
        {
            messageForm mform = new messageForm();
            mform.StartPosition = FormStartPosition.CenterScreen;
            mform.Show();
            mform.ShowMessage(message.ToString(), 2000);
        }
        #endregion

        #region 创建多线程
        /// <summary>
        /// 创建多线程，避免程序因等待时间过长而出现假死现象，影响用户体验
        /// </summary>
        /// <param name="type"></param>
        private void OpenThread(string type)
        {
            try
            {
                //if (this.cbOnLine.Checked == true)
                //{
                Thread thread = null;
                switch (type)
                {
                    case "cycle":
                        thread = new Thread(new ThreadStart(CycleCheck));
                        break;
                    case "workNo":
                        thread = new Thread(new ThreadStart(CheckWorkNo));
                        break;
                    case "mesStatus":
                        thread = new Thread(new ThreadStart(ConnectMes));
                        break;
                    case "testNo":
                        thread = new Thread(new ThreadStart(CheckTestNo));
                        break;
                    case "readCarNo":
                        thread = new Thread(new ThreadStart(ReadPlc));
                        break;
                }
                thread.IsBackground = true;
                thread.Start();
                //}
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region 读取小车流水号
        /// <summary>
        /// 用于刷新小车流水号，一分钟执行一遍
        /// </summary>
        private void ReadPlc()
        {
            try
            {

                string SmallCarNo = null;
                string ReadPLCSmallCard = "D1122";

                for (int k = 0; k < 10; k++)
                {
                    string PLCAddress = ReadPLCSmallCard;
                    PLCAddress += k.ToString();
                    var receiveDataSM = opc.ReadData(ChanneOtherDevice + PLCAddress);
                    try
                    {
                        int AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) % 256);
                        SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                        AscciiData = Convert.ToInt32(Convert.ToInt32(receiveDataSM) / 256);
                        SmallCarNo += ASCIIConvertString.Chr(AscciiData);
                    }
                    catch (Exception exs)
                    { }

                }
                if (SmallCarNo != null)
                {
                    if (SmallCarNo.Length == 20)
                    {
                        this.Invoke(new MesResult(PLC_Result), SmallCarNo);
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 更新小车流水号
        /// </summary>
        /// <param name="c"></param>
        private void PLC_Result(object c)
        {
            try
            {
                if (!c.ToString().Equals(tbInputCarNo.Text))
                {
                    plcCarNo = tbInputCarNo.Text = c.ToString();
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region 实验单号校验
        /// <summary>
        /// 实验单号校验
        /// </summary>
        private void CheckTestNo()
        {
            try
            {
                string printMessage = "";
                JObject jobject = new JObject();
                jobject.Add("sn", testNo);
                jobject.Add("test", true);

                deviceData.AccessToken = AccessToken;
                deviceData.EquipmentID = EquipmentID;
                deviceData.UserID = UserID;
                deviceData.Type = "verify";
                deviceData.Data = jobject.ToString();
                bool mesResult, mesVerify;
                string mesCode;
                string mesResponse, webServiceSign;
                if (new ConnectWebService().WebService(deviceData, out mesResult, out mesVerify, out mesCode, out mesResponse, out webServiceSign))
                {
                    if (mesVerify == true)
                    {
                        printMessage = "实验单号校验成功！\r\n服务器返回：" + mesResponse.ToString();
                        this.Invoke(new MesCheckResult(CheckTestNoResult), new object[] { printMessage, "true", null });
                    }
                    else
                    {
                        printMessage = "实验单号校验失败！\r\n失败代码：" + mesCode + "\r\n服务器返回：" + mesResponse.ToString();
                        this.Invoke(new MesCheckResult(CheckTestNoResult), new object[] { printMessage, "false", null });
                    }
                }
                else
                {
                    printMessage = "MES服务器没有响应！";
                    //服务器没有响应默认通过校验
                    this.Invoke(new MesCheckResult(CheckTestNoResult), new object[] { printMessage, "true", null });

                    //重连服务器
                    Thread.Sleep(200);
                    ConnectMes();
                }
                PrintLog(printMessage);
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 实验单号校验结果反馈到UI界面（主线程执行）
        /// </summary>
        /// <param name="message"></param>
        /// <param name="type"></param>
        /// <param name="dataTable"></param>
        private void CheckTestNoResult(string message, string type, DataTable dataTable)
        {
            this.tbMessage.Text = message;
            if (type.Equals("true"))
            {
                this.tbShowTestNo.Text = this.tbTestNo.Text;
                this.tbTestNo.Enabled = false;
                this.tbTestNo.BackColor = Color.LightGreen;
            }
            else
            {
                this.cbTestNo.Checked = false;
            }
        }
        #endregion

        #region 工号登录校验
        /// <summary>
        /// 工号登录按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (tbUser.Text == "")
                {
                    MessageBox.Show("请输入工号");
                    return;
                }
                else
                {
                    if (this.tbUser.Text.Trim().ToUpper().Equals("ADMIN"))
                    {
                        this.tbShowUser.Text = "ADMIN";
                        this.tbUser.Enabled = false;
                        this.tbUser.BackColor = Color.LightGreen;
                        this.tbMessage.Text = "登录成功！";

                        this.textBox1.Show();
                        this.button1.Show();
                        this.label1.Show();
                        this.button2.Show();
                    }
                    else
                    {
                        if (this.tbUser.Text.Trim().Length > 8)
                        {
                            MessageBox.Show("工号长度不能超过8位.");
                        }
                        else
                        {
                            if (this.tbUser.Text.Trim().Equals(this.tbShowUser.Text.Trim()))
                            {
                                this.tbMessage.Text = "工号已经登录！";
                                return;
                            }

                            this.tbUser.Text = tbUser.Text.ToUpper();
                            UserID = this.tbUser.Text.Trim();

                            if (this.tbMesStatus.Text.Trim() == "在线")
                            {
                                tbMessage.Text = "校验工号";
                                //创建多线程，避免程序因等待时间过长而出现假死现象
                                OpenThread("workNo");
                            }
                            else
                            {
                                this.tbShowUser.Text = this.tbUser.Text;
                                this.tbUser.Enabled = false;
                                this.tbUser.BackColor = Color.LightGreen;
                                this.tbMessage.Text = "登录成功！";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 多线程中校验工号，校验完毕再将校验结果反馈到UI界面，避免等待时间过长，客户端出现假死现象
        /// </summary>
        private void CheckWorkNo()
        {
            try
            {
                JObject jObject = new JObject();
                jObject.Add("user", UserID);
                //this.tbMessage.Text = "正在校验工号...";

                bool result = SubmitToMesTest("validate", jObject.ToString(), null);

                this.Invoke(new MesResult(CheckWorkNoResult), result);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 将工号校验结果反馈到UI界面（主线程执行）
        /// </summary>
        /// <param name="result">校验结果</param>
        private void CheckWorkNoResult(object result)
        {
            if ((bool)result)
            {
                this.tbShowUser.Text = this.tbUser.Text;
                this.tbUser.Enabled = false;
                this.tbUser.BackColor = Color.LightGreen;
            }
        }

        #endregion

        #region 退出工号登录
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbShowUser.Text.Trim().Equals("99999"))
                {
                    return;
                }
                else
                {
                    if (this.tbUser.Text.Trim().ToUpper().Equals("ADMIN"))
                    {
                        this.textBox1.Hide();
                        this.button1.Hide();
                        this.label1.Hide();
                        this.button2.Hide();
                    }
                    this.tbUser.Text = "";
                    this.tbUser.Enabled = true;
                    this.tbUser.BackColor = Color.White;
                    this.tbShowUser.Text = "99999";
                    UserID = "99999";
                    this.tbMessage.Text = "退出成功！";
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 生产信息实时刷新
        /// <summary>
        /// 默认一分钟执行一次，用于收集生产信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerProduct_Tick(object sender, EventArgs e)
        {
            this.timerProduct.Enabled = false;
            staCycle++;

            //创建多线程，避免程序因查询时间过长而出现的假死现象，影响用户体验
            //通过timer隔一段时间开启线程
            OpenThread("cycle");

            if (staCycle == 6)
            {
                staCycle = 0;
            }

            this.timerProduct.Enabled = true;
        }
        /// <summary>
        /// 后台循环收集信息
        /// </summary>
        private void CycleCheck()
        {
            //if (this.cbOnLine.Checked == true)
            try
            {
                //读取小车流水号
                ReadPlc();
                Thread.Sleep(200);

                string timeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");//
                //一分钟之前
                string timeS = DateTime.Parse(timeNow).AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss");

                string carNo = "";


                //绑定小车流水号
                UpdateCarNo(timeS, timeNow);
                Thread.Sleep(500);

                //设备报警
                SubmitWarning(timeS, timeNow);
                Thread.Sleep(2000);
                //生产过程
                SubmitProcess(timeS, timeNow);
                Thread.Sleep(2000);
                //生产结果
                SubmitProduct(timeS, timeNow);
                //设备状态
                SubmitStatus(staCycle, timeS, timeNow);
                Thread.Sleep(2000);
                if (this.cbOnLine.Checked == true)
                {
                    if (this.IfOnLine == false)
                    {
                        ConnectMes();
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 小车流水号跟电池绑定
        /// </summary>
        /// <param name="timeS"></param>
        /// <param name="timeNow"></param>
        private void UpdateCarNo(string timeS, string timeNow)
        {
            string sqlStr = "";
            try
            {
                objIEqAlarm_BLL = new EqAlarm_BLL();
                sqlStr = "select top 1 小车流水号 from HK_EqStationInfo where 工位='预热过渡段' order by 采集时间 desc";
                //sqlStr = string.Format("select 小车流水号 from HK_EqStationInfo where 工位='预热过渡段' and 采集时间>'{0}'and 采集时间<='{1}'",
                //  timeS, timeNow);
                DataTable dataTable = new DataBaseOperate().loadDate(sqlStr);
                // objIEqAlarm_BLL.getData(sqlStr);
                if (dataTable.Rows.Count != 0)
                {
                    sqlStr = string.Format("update HK_EqProductInfo set 小车流水号='{0}' where 电池二维码 in (select top 718 电池二维码  from" +
                            " HK_EqProductInfo where 小车流水号='' order by 扫码时间 asc)", dataTable.Rows[0]["小车流水号"].ToString());
                    new DataBaseOperate().loadDate(sqlStr);
                    //objIEqAlarm_BLL = new EqAlarm_BLL();
                    //objIEqAlarm_BLL.ExecuteNonQuery(sqlStr, null);
                    // PrintLog("小车：" + dataTable.Rows[0]["小车流水号"].ToString() + "与电池绑定成功");
                }
            }
            catch (Exception ex)
            {

                PrintLog(sqlStr + "\r\n :" + ex.ToString());
            }
        }

        /// <summary>
        /// 生产过程信息
        /// </summary>
        /// <param name="DBO"></param>
        /// <param name="sqlStr"></param>
        /// <param name="dataTable"></param>
        /// <param name="timeS"></param>
        /// <param name="timeNow"></param>
        private void SubmitProcess(string timeS, string timeNow)
        {
            try
            {
                string sqlStr = null;
                DataTable dataTable = new DataTable();
                objIEqAlarm_BLL = new EqAlarm_BLL();
                //Console.WriteLine("生产过程：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //PrintLog("生产过程提交");
                foreach (var station in stations)
                {
                    sqlStr = "select distinct top 1 工位,小车流水号,Convert(decimal(18,2),温度SV) as 温度SV ,Convert(decimal(18,2),温度测量值PV1) as 温度测量值PV1 ,Convert(decimal(18,2),温度测量值PV2) as 温度测量值PV2,真空度高限SV,真空度低限SV,真空度PV,采集时间 from HK_EqTechnologyParameterInfo where   (IsUpMes is null or IsUpMes =0)  and 工位='" +
                        station + "'  order by 采集时间 desc";

                    DataBaseOperate DBO = new DataBaseOperate();
                    dataTable = DBO.loadDate(sqlStr);
                    //objIEqAlarm_BLL = new EqAlarm_BLL();
                    //dataTable = objIEqAlarm_BLL.getData(sqlStr);
                    if (dataTable.Rows.Count != 0)
                    {
                        if (dataTable.Rows[0]["小车流水号"].ToString().Equals("") || dataTable.Rows[0]["小车流水号"].ToString().Equals("0"))
                        {
                            continue;
                        }

                        ////MES服务器在线提交数据，离线则保存到本地，恢复在线再一并提交。
                        //if (this.cbOnLine.Checked == true && this.IfOnLine == true)
                        //{

                        sqlStr = "select 电池二维码,扫码时间 from HK_EqProductInfo where 小车流水号='" + dataTable.Rows[0]["小车流水号"] + "'";
                        //  DataTable cellTable = objIEqAlarm_BLL.getData(sqlStr);
                        DataTable cellTable = DBO.loadDate(sqlStr);
                        if (cellTable.Rows.Count != 0)
                        {
                            JObject jObject = new JObject();
                            JArray cellArray = new JArray();
                            string[] value;
                            JArray valArray;
                            foreach (DataRow item in cellTable.Rows)
                            {
                                valArray = new JArray();
                                value = new string[2];
                                value[0] = item["电池二维码"].ToString();
                                value[1] = DateTime.Parse(item["扫码时间"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                                valArray.Add(value);
                                cellArray.Add(valArray);
                            }

                            JArray procArray = new JArray() { dataTable.Rows[0]["小车流水号"],DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),dataTable.Rows[0]["工位"],dataTable.Rows[0]["温度SV"],dataTable.Rows[0]["温度测量值PV1"],
                                dataTable.Rows[0]["温度测量值PV2"],dataTable.Rows[0]["真空度高限SV"],dataTable.Rows[0]["真空度低限SV"],dataTable.Rows[0]["真空度PV"] };

                            jObject.Add("outSN", cellArray);
                            jObject.Add("proc", procArray);
                            PrintLog("过程数据在线提交");
                            string strSql = string.Format("Update    HK_EqTechnologyParameterInfo set IsUpMes = '1' where    工位='{0}'   and 小车流水号='{1}' ", station, dataTable.Rows[0]["小车流水号"]);
                            if (SubmitToMesTest("process", jObject.ToString(), dataTable))
                            {
                                strSql = string.Format("Update    HK_EqTechnologyParameterInfo set IsUpMes = '1' where    工位='{0}'   and 小车流水号='{1}' ", station, dataTable.Rows[0]["小车流水号"]);

                                objIEqAlarm_BLL.ExecuteNonQuery(strSql, null);

                            }
                        }
                        //}
                        //else
                        //{
                        //    //  PrintLog("离线缓存");
                        //    //缓存方法，提交小车流水号、采集时间和工位等数据。
                        //    SaveBuffer("process", dataTable);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n 操作生产过程数据时发生系统错误！";
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { message, null, null });
                PrintLog(ex.ToString());
            }
        }


        /// <summary>
        /// 设备报警信息
        /// </summary>
        /// <param name="DBO"></param>
        /// <param name="sqlStr"></param>
        /// <param name="dataTable"></param>
        /// <param name="timeS"></param>
        /// <param name="timeNow"></param>
        private void SubmitWarning(string timeS, string timeNow)
        {
            try
            {
                DataTable dataTable = new DataTable();
                string sqlStr = null;
                //  Console.WriteLine("生产报警：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStr = "select AlarmID,AlmName,TimeS,TimeE,Info from HK_EqAlarmInfo where TimeS >'" + timeS + "'and TimeS <='" + timeNow + "'";
                //sqlStr = "select top 1 AlarmID,AlmName,TimeS,TimeE,Info from HK_EqAlarmInfo order by TimeS desc";

                dataTable = objIEqAlarm_BLL.getData(sqlStr);

                //一分钟循环监控一遍，有新纪录立即上传
                if (dataTable.Rows.Count != 0)
                {

                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        sqlStr = "select top 20 AlarmID,AlmName,TimeS,TimeE,Info from HK_EqAlarmInfo order by TimeS desc";

                        JObject jobject = new JObject();
                        jobject.Add("code", dataTable.Rows[i]["AlmName"].ToString());
                        SubmitToMesTest("warning", jobject.ToString(), objIEqAlarm_BLL.getData(sqlStr));
                    }
                }
            }
            catch (Exception ex)
            {
                string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n 操作生产报警数据时发生系统错误！";
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { message, null, null });
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 设备状态信息
        /// </summary>
        /// <param name="DBO"></param>
        /// <param name="sql"></param>
        /// <param name="dataTable"></param>
        /// <param name="staCycle"></param>
        /// <param name="timeS"></param>
        /// <param name="timeNow"></param>
        private void SubmitStatus(int staCycle, string timeS, string timeNow)
        {
            try
            {
                DataTable dataTable = new DataTable();
                string sqlStr = null;
                //Console.WriteLine("设备状态：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                objIEqAlarm_BLL = new EqAlarm_BLL();

                sqlStr = "select DISTINCT 设备编号,设备状态,故障代码,采集时间 from HK_EqStatusInfo where 采集时间 > '" + timeS + "'and 采集时间 <= '" + timeNow + "'";
                //sql = "select top 1 设备编号,设备状态,故障代码,采集时间 from HK_EqStatusInfo order by 采集时间 desc";
                dataTable = objIEqAlarm_BLL.getData(sqlStr);
                //一分钟循环监控一遍，有新纪录立即上传，没有新纪录循环5次上传，即5分钟上传一次设备状态记录
                if (dataTable.Rows.Count != 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        sqlStr = "select DISTINCT top 50 设备编号,设备状态,故障代码,采集时间 from HK_EqStatusInfo order by 采集时间 desc";
                        //DBO.loadDate(sql);
                        JObject jobject = new JObject();
                        jobject.Add("status", "40");
                        jobject.Add("code", dataTable.Rows[i]["故障代码"].ToString());
                        SubmitToMesTest("status", jobject.ToString(), objIEqAlarm_BLL.getData(sqlStr));
                    }
                    staCycle = 0;
                }
                if (staCycle == 5)
                {
                    sqlStr = "select DISTINCT top 50 设备编号,设备状态,故障代码,采集时间 from HK_EqStatusInfo order by 采集时间 desc";
                    JObject jobject = new JObject();
                    jobject.Add("status", "10");
                    jobject.Add("code", "");
                    dataTable = objIEqAlarm_BLL.getData(sqlStr);
                    PrintLog("准备上传MES设备状态数据");
                    if (SubmitToMesTest("status", jobject.ToString(), dataTable))
                    {
                        PrintLog("设备状态数据，上传MES成功");
                    }
                    else
                    {
                        PrintLog("设备状态数据，上传MES失败");
                    }
                    staCycle = 0;
                }
            }
            catch (Exception ex)
            {
                string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n 操作设备状态数据时发生系统错误！";
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { message, null, null });
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 生产结果信息
        /// </summary>
        /// <param name="DBO"></param>
        /// <param name="carNo"></param>
        /// <param name="sql"></param>
        /// <param name="dataTable"></param>
        /// <param name="timeS"></param>
        /// <param name="timeNow"></param>
        private void SubmitProduct(string timeS, string timeNow)
        {
            try
            {
                DataBaseOperate DBO = new DataBaseOperate();
                string inTime = null;
                string tempStrSql = "select top 1 小车流水号,采集时间,工位 from dbo.HK_EqStationInfo t1" +
                 " where t1.工位 = '下料台' and t1.小车流水号 in (select distinct t2.小车流水号 from HK_EqStationInfo t2 inner join HK_EqProductInfo t3 on t2.小车流水号 = t3.小车流水号" +
                " where t2.工位 = '上料台')    and (IsUpMes is null or IsUpMes = '0')  order by 采集时间 desc ";

                // string tempStrSql = "select distinct top 1 小车流水号,采集时间,工位 from HK_EqStationInfo where 工位='下料台' and ( IsUpMes is null or IsUpMes = '0')  order by 采集时间 desc ";
                objIEqAlarm_BLL = new EqAlarm_BLL();

                DataTable dataTable = objIEqAlarm_BLL.getData(tempStrSql);
                if (dataTable.Rows.Count != 0)
                {
                    string carNo = dataTable.Rows[0]["小车流水号"].ToString().Trim();
                    string outTime = DateTime.Parse(dataTable.Rows[0]["采集时间"].ToString().Trim()).ToString("yyyy-MM-dd HH:mm:ss");
                    if (string.IsNullOrEmpty(carNo))
                    {
                        return;
                    }

                    this.Invoke(new MethodInvoker(delegate { this.tbOutputNo.Text = carNo; }));

                    //MES服务器在线提交数据，离线则保存到本地，恢复在线再一并提交。
                    if (this.cbOnLine.Checked == true && this.IfOnLine == true)
                    {

                        string tempStr = string.Format("select distinct 小车流水号,采集时间 from HK_EqStationInfo where 工位='预热过渡段'  and 小车流水号='{0}'", carNo);
                        objIEqAlarm_BLL = new EqAlarm_BLL();
                        DataTable flagTable = objIEqAlarm_BLL.getData(tempStr);
                        if (flagTable.Rows.Count > 0)
                        {
                            inTime = DateTime.Parse(flagTable.Rows[0]["采集时间"].ToString().Trim()).ToString("yyyy-MM-dd HH:mm:ss");

                        }
                        int abnormal_number = flagTable.Rows.Count - 1;

                        tempStrSql = string.Format("select 电池代码,电池二维码,设备编号,小车流水号,扫码时间,测试结果 from HK_EqProductInfo  where 小车流水号= '{0}' order by 扫码时间", carNo);
                        objIEqAlarm_BLL = new EqAlarm_BLL();
                        DataTable cellTable = objIEqAlarm_BLL.getData(tempStrSql);
                        if (cellTable.Rows.Count != 0)
                        {
                            PrintInsertLog("生产结果提交,小车号" + carNo);
                            //封装json数据
                            JArray jArray = new JArray();
                            JObject jObject = new JObject();
                            string[] value;
                            JArray valArray;
                            foreach (DataRow item in cellTable.Rows)
                            {
                                valArray = new JArray();
                                value = new string[2];
                                value[0] = item["电池二维码"].ToString();
                                value[1] = DateTime.Parse(item["扫码时间"].ToString().Trim()).ToString("yyyy-MM-dd HH:mm:ss");
                                valArray.Add(value);
                                jArray.Add(valArray);
                            }
                            JObject valObject = new JObject();
                            valObject.Add("abnormal_number", abnormal_number);
                            valObject.Add("water", "");
                            jObject.Add("ok", true);
                            jObject.Add("test", testNo);
                            jObject.Add("inSN", jArray);
                            jObject.Add("outSN", carNo);
                            jObject.Add("inTime", inTime);
                            jObject.Add("outTime", outTime);
                            jObject.Add("mtSN", new JArray());
                            jObject.Add("prop", valObject);

                            if (SubmitToMesTest("product", jObject.ToString(), dataTable))
                            {
                                string strSql = string.Format("update HK_EqStationInfo set IsUpMes ='1' where 小车流水号 ='{0}'", carNo);

                                objIEqAlarm_BLL = new EqAlarm_BLL();
                                objIEqAlarm_BLL.ExecuteNonQuery(strSql, null);
                                strSql = string.Format("Update    HK_EqTechnologyParameterInfo set IsUpMes = '1' where  小车流水号='{0}' ", carNo);

                                objIEqAlarm_BLL.ExecuteNonQuery(strSql, null);
                                try
                                {
                                    string sqlStrTemp = "delete HK_EqTechnologyParameterInfo where 采集时间  <'" + DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd HH:mm:ss") + "'";
                                    objIEqAlarm_BLL = new EqAlarm_BLL();
                                    objIEqAlarm_BLL.ExecuteNonQuery(sqlStrTemp, null);
                                    PrintInsertLog("结果数据在线提交，成功处理状态！");
                                }
                                catch (Exception exe)
                                { }
                            }

                            this.Invoke(new MethodInvoker(delegate { this.outputDataGridView.DataSource = cellTable; }));
                        }
                    }

                    carNo = "";
                }
            }
            catch (Exception ex)
            {
                string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n 操作生产结果数据时发生系统错误！";
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { message + ex.ToString(), null, null });
                PrintLog(ex.ToString());
            }
        }

        #endregion


        #region 数据发送至MES服务器
        /// <summary>
        /// 将数据发送至MES服务器（多线程执行）
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        private bool SubmitToMesTest(string type, string data, DataTable dataTable)
        {
            string resultType = "";
            try
            {
                deviceData.AccessToken = AccessToken;
                deviceData.EquipmentID = EquipmentID;
                deviceData.UserID = UserID;
                deviceData.Type = type;
                deviceData.Data = data;
                bool mesResult, mesVerify;
                string mesCode;
                string mesResponse, webServiceSign;
                string printMessage = "";

                switch (type)
                {
                    case "validate":
                        resultType = "工号检验";
                        break;
                    case "status":
                        resultType = "设备状态提交";
                        break;
                    case "warning":
                        resultType = "设备报警提交";
                        break;
                    case "verify":
                        resultType = "来料校验";
                        break;
                    case "product":
                        resultType = "生产结果提交";
                        printMessage = "生产结果提交，等待上传:" + DateTime.Now.ToString();
                        PrintInsertLog(printMessage);
                        break;
                    case "process":
                        resultType = "生产过程提交";
                        break;
                }
                //调用webservice，有返回结果为true，否则为false(表示服务器无响应，代表服务器可能不在线)
                if (new ConnectWebService().WebService(deviceData, out mesResult, out mesVerify, out mesCode, out mesResponse, out webServiceSign))
                {
                    //MES服务器返回结果不为空为true
                    if (mesResult == true)
                    {

                        //校验结果
                        if (mesVerify == true)
                        {
                            printMessage = resultType + "成功！\r\n服务器返回:" + mesResponse.ToString();
                            if (resultType != "设备状态提交")
                            {
                                PrintLog(printMessage);
                            }
                            if (type.Equals("product"))
                            {
                                PrintInsertLog(printMessage);
                            }
                            this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { printMessage, type, dataTable });
                            return true;
                        }
                        else
                        {
                            printMessage = resultType + "失败！\r\n失败代码：" + mesCode + "\r\n服务器返回：" + mesResponse.ToString();
                        }
                    }
                    else
                    {
                        printMessage = resultType + "出现异常！\r\n错误代码：" + mesCode + "\r\n服务器返回：" + mesResponse.ToString();
                    }
                    //将结果反馈到UI
                    this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { printMessage, type, dataTable });
                    if (resultType != "设备状态提交")
                    {
                        PrintLog(printMessage);
                    }

                }
                else
                {
                    printMessage = resultType + "失败！服务器没有响应。";
                    this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { printMessage, "connetFalt", dataTable });
                    PrintLog(printMessage);
                    //服务器重连
                    Thread.Sleep(200);
                    ConnectMes();
                    return true;
                }

            }
            catch (Exception ex)
            {
                this.Invoke(new MesCheckResult(PrintMesRusult), new object[] { resultType.Substring(0, 4) + "发送数据至MES服务器时发生错误！", "", null });
                PrintLog(ex.StackTrace.ToString());
            }
            return false;
        }
        /// <summary>
        /// 反馈MES返回结果（主线程执行）
        /// </summary>
        /// <param name="message"></param>
        /// <param name="type"></param>
        /// <param name="dataTable"></param>
        private void PrintMesRusult(string message, string type, DataTable dataTable)
        {
            this.tbMessage.Text = message;
            switch (type)
            {
                case "status":
                    this.EqStatusDataGridView.DataSource = dataTable;
                    break;
                case "warning":
                    this.AlarmDataGridView.DataSource = dataTable;
                    break;
                case "product":
                    this.outputDataGridView.DataSource = dataTable;
                    break;
                case "process":
                    //  this.ProcessDataGridView.DataSource = dataTable;
                    break;
                case "connetFalt":
                    Thread.Sleep(500);
                    this.tbMessage.Text = "重新连接服务器";
                    break;
            }
        }


        #endregion

        #region 单选框勾选事件
        /// <summary>
        /// checkbox的勾选时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.ActiveControl != null)
                {
                    switch (this.ActiveControl.Name)
                    {
                        case "cbOnLine":
                            if (this.cbOnLine.Checked == true)
                            {
                                tbMessage.Text = "正在连接MES服务器...";
                                this.cbOutLine.Checked = false;
                                OpenThread("mesStatus");
                            }
                            else
                            {
                                this.IfOnLine = true;
                                this.cbOnLine.Checked = true;
                            }

                            break;
                        case "cbOutLine":
                            if (cbOutLine.Checked == true)
                            {
                                this.tbMesStatus.Text = "离线";
                                this.tbMesStatus.BackColor = Color.Red;
                                this.cbOnLine.Checked = false;
                                this.tbMessage.Text = "MES系统处于离线状态！";
                                //记录MES服务器状态
                                this.IfOnLine = false;
                            }
                            else
                            {
                                //记录MES服务器状态
                                this.IfOnLine = false;
                                this.cbOutLine.Checked = true;
                            }
                            break;
                        case "cbOn":
                            if (cbOn.Checked == true)
                            {
                                this.cbOff.Checked = false;
                                //记录校验状态
                                this.IfCheck = true;
                            }
                            else
                            {
                                this.cbOn.Checked = true;
                                //记录校验状态
                                this.IfCheck = true;
                            }
                            break;
                        case "cbOff":
                            if (cbOff.Checked == true)
                            {
                                this.cbOn.Checked = false;
                                //记录校验状态
                                this.IfCheck = false;
                            }
                            else
                            {
                                this.cbOff.Checked = true;
                                //记录校验状态
                                this.IfCheck = false;
                            }
                            break;
                        case "cbTestNo":
                            if (cbTestNo.Checked == true)
                            {
                                if (this.tbTestNo.Text == "")
                                {
                                    this.cbTestNo.Checked = false;
                                    MessageBox.Show("请输入实验单号！");
                                    break;
                                }
                                else
                                {
                                    //记录实验单号
                                    testNo = this.tbTestNo.Text.Trim();
                                    string filePath = Application.StartupPath + "\\Config.ini";
                                    ConfigOperate.WriteIniKeys("CONFIG", "testNo", this.tbTestNo.Text.Trim(), filePath);
                                    if (this.IfOnLine)
                                    {
                                        OpenThread("testNo");
                                    }
                                    else
                                    {
                                        this.tbShowTestNo.Text = this.tbTestNo.Text;
                                        this.tbTestNo.Enabled = false;
                                        this.tbTestNo.BackColor = Color.LightGreen;
                                        this.tbMessage.Text = "实验单号校验成功！";
                                    }
                                }
                            }
                            else
                            {
                                //记录实验单号
                                testNo = "";// testNo = "4237.21";

                                this.tbShowTestNo.Text = "";
                                this.tbTestNo.Text = "";
                                this.tbTestNo.Enabled = true;
                                this.tbTestNo.BackColor = Color.White;
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region MES在线、离线校验
        /// <summary>
        /// 将校验结果显示在界面上，本方法是在UI主线程执行的。
        /// </summary>
        /// <param name="result">校验结果</param>
        private void ConnectMesResult(object result)
        {
            if ((bool)result)
            {
                this.tbMesStatus.Text = "在线";
                this.tbMesStatus.BackColor = Color.LimeGreen;
                this.cbOnLine.Checked = true;
                this.tbMessage.Text = "MES服务器连接成功！";
                //记录MES服务器状态
                this.IfOnLine = true;
            }
            else
            {
                this.tbMesStatus.Text = "离线";
                this.tbMesStatus.BackColor = Color.Red;
                this.cbOnLine.Checked = true;
                this.tbMessage.Text = "MES系统处于离线状态！";
                //记录MES服务器状态
                this.IfOnLine = false;
            }
        }

        /// <summary>
        /// 连接MES服务器。在多线程中连接MES服务器，有返回结果再显示在界面上。
        /// </summary>
        private void ConnectMes()
        {
            try
            {
                JObject jobject = new JObject();
                jobject.Add("status", "10");
                jobject.Add("code", "");

                deviceData.AccessToken = AccessToken;
                deviceData.EquipmentID = EquipmentID;
                deviceData.UserID = UserID;
                deviceData.Type = "status";
                deviceData.Data = jobject.ToString();
                bool mesResult, mesVerify;
                string mesCode;
                string mesResponse, webServiceSign;

                //将数据发送至mes服务器，此处有几率会阻塞，故放置于多线程中运行
                bool result = new ConnectWebService().WebService(deviceData, out mesResult, out mesVerify, out mesCode, out mesResponse, out webServiceSign);

                //将返回结果显示在主线程界面
                this.Invoke(new MesResult(ConnectMesResult), result);

                //服务器恢复在线状态，将离线缓存的数据提交到MES服务器
                //if (result)
                //{
                //    //读取缓存数据
                //    DataTable dataTable = ReadBuffer();
                //    if (dataTable.Rows.Count!=0)
                //    {
                //        //保存数据
                //        SubmitBufferData(dataTable);
                //    }
                //}
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region textbox回车事件
        private void textBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                switch (this.ActiveControl.Name)
                {
                    case "tbUser":
                        this.btnLogin.PerformClick();
                        break;
                    case "tbTestNo":
                        this.cbTestNo.Checked = true;
                        if (this.tbTestNo.Text == "")
                        {
                            this.cbTestNo.Checked = false;
                            MessageBox.Show("请输入实验单号！");
                            break;
                        }
                        else
                        {
                            //记录实验单号
                            testNo = this.tbTestNo.Text.Trim();

                            if (this.IfOnLine)
                            {
                                OpenThread("testNo");
                            }
                            else
                            {
                                this.tbShowTestNo.Text = this.tbTestNo.Text;
                                this.tbTestNo.Enabled = false;
                                this.tbTestNo.BackColor = Color.LightGreen;
                                this.tbMessage.Text = "实验单号校验成功！";
                            }
                        }
                        break;
                    case "tbServerAddress":
                        this.tbAccessToken.Focus();
                        break;
                    case "tbAccessToken":
                        this.tbEquipmentID.Focus();
                        break;
                    case "tbEquipmentID":
                        this.btnSet.PerformClick();
                        break;
                }
            }
        }
        #endregion

        #region 配置文件设置
        private void btnSet_Click(object sender, EventArgs e)
        {
            try
            {


                string filePath = Application.StartupPath + "\\Config.ini";

                ConfigOperate.WriteIniKeys("CONFIG", "ServerAddress", this.tbServerAddress.Text.Trim(), filePath);
                ConfigOperate.WriteIniKeys("CONFIG", "AccessToken", this.tbAccessToken.Text.Trim(), filePath);
                ConfigOperate.WriteIniKeys("CONFIG", "EquipmentID", this.tbEquipmentID.Text.Trim(), filePath);
                ConfigOperate.WriteIniKeys("SerialPort", "PortName", this.comList.Text.Trim(), filePath);
                ConfigOperate.WriteIniKeys("BatCif", "BatLength", this.txtBatLength.Text.Trim(), filePath);
                //ConfigOperate.WriteIniKeys("SerialPort", "BaudRate", Convert.ToInt32(9600).ToString(), filePath);
                //ConfigOperate.WriteIniKeys("SerialPort", "DataBits", Convert.ToInt32(8).ToString(), filePath);
                //ConfigOperate.WriteIniKeys("SerialPort", "StopBits", Convert.ToInt32(1).ToString(), filePath);
                //ConfigOperate.WriteIniKeys("SerialPort", "Parity", Parity.None.ToString(), filePath);

                //授权码
                AccessToken = this.tbAccessToken.Text.Trim();
                //设备编号
                EquipmentID = this.tbEquipmentID.Text.Trim();

                this.tbMessage.Text = "设置成功！";
            }
            catch (Exception)
            {
                this.tbMessage.Text = "设置失败！";
            }
        }
        #endregion

        #region 程序最小化到系统托盘
        //双击托盘图标还原程序
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }
        //关闭程序时最小化到系统托盘
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            this.notifyIcon1.Visible = true;
        }
        //右键程序的图标会有三个选项：显示窗口、隐藏窗口、退出程序
        //这是第一个选项：显示窗口
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        //第二个选项：隐藏窗口
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
        //第三个选项：退出程序
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序？", "安全提示", System.Windows.Forms.MessageBoxButtons.YesNo,
                System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    //  notifyIcon1.Visible = false;//系统托盘图标不可见
                    this.Dispose();//释放资源
                    notifyIcon1.Dispose();
                    thdAutoMove.Abort();
                    this.Close();//关闭窗体 
                    Application.Exit();//关闭应用程序窗体 
                    Application.ExitThread(); //强制中止调用线程上的所有消息，同样面临其它线程无法正确退出的问题；
                    System.Environment.Exit(0); //这是最彻底的退出方式，不管什么线程都被强制退出，把程序结束的很干净。
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    GC.Collect();
                }
            }
        }
        #endregion

        #region 解除配置功能的锁定状态
        private void btnUnlock_Click(object sender, EventArgs e)
        {
            if (this.btnUnlock.Text.Equals("解锁"))
            {
                this.tbServerAddress.Enabled = true;
                this.tbServerAddress.BackColor = Color.White;

                this.tbAccessToken.Enabled = true;
                this.tbAccessToken.BackColor = Color.White;

                this.tbEquipmentID.Enabled = true;
                this.tbEquipmentID.BackColor = Color.White;

                this.comList.Enabled = true;
                this.comList.BackColor = Color.White;

                this.btnOpen.Enabled = true;

                this.btnSet.Enabled = true;
                this.btnKepServerConfig.Enabled = true;
                this.txtBatLength.Enabled = true;
                this.btnUnlock.Text = "锁定";

                txtPlcAddress.Enabled = true;
                cboStation.Enabled = true;
            }
            else
            {
                cboStation.Enabled = false;
                txtPlcAddress.Enabled = false;
                this.tbServerAddress.Enabled = false;
                this.tbServerAddress.BackColor = Color.LightGreen;

                this.tbAccessToken.Enabled = false;
                this.tbAccessToken.BackColor = Color.LightGreen;

                this.tbEquipmentID.Enabled = false;
                this.tbEquipmentID.BackColor = Color.LightGreen;

                this.comList.Enabled = false;
                this.comList.BackColor = Color.LightGreen;

                this.btnOpen.Enabled = false;

                this.btnSet.Enabled = false;

                this.btnUnlock.Text = "解锁";
            }
        }
        #endregion

        #region 设定循环时间
        /// <summary>
        /// 该功能只有登录工号“admin”才能使用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.timerProduct.Interval = 2000 * Convert.ToInt32(this.textBox1.Text.Trim());
            this.timerProduct.Enabled = true;
        }
        #endregion

        #region 打印日记
        /// <summary>
        /// 根据日期生成文件夹，如：D:\MES_Logs\2017年7月20日
        /// 文件夹只保留3个月
        /// </summary>
        /// <param name="message"></param>
        public void PrintLog(string message)
        {
            try
            {
                DateTime timeN = DateTime.Now;
                string directory = "d:\\MES_Logs\\" + timeN.ToLongDateString();
                //string delDir = "d:\\MES_Logs\\" + timeN.AddMonths(-3).ToLongDateString();
                //生成文件夹
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                ////删除文件夹。第二个参数选true，表示删除该目录的子目录及子文件；如果选false，则该目录不为空时不能删除
                //if (Directory.Exists(delDir))
                //{
                //    Directory.Delete(delDir, true);
                //}
                File.AppendAllText(directory + "\\" + timeN.ToString("yyyyMMddHH") + ".log", "************************" +
                    timeN.ToString("yyyy-MM-dd HH:mm:ss") + "***************************\r\n" + message + "\r\n");
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        /// <summary>
        /// 根据日期生成文件夹，如：D:\MES_Logs\2017年7月20日
        /// 文件夹只保留3个月
        /// </summary>
        /// <param name="message"></param>
        public void PrintInsertLog(string message, string PathDir = "d:/MES_Insert_Logs/")
        {
            try
            {
                DateTime timeN = DateTime.Now;
                string directory = PathDir + timeN.ToLongDateString();
                //  string delDir = PathDir + timeN.AddMonths(-3).ToLongDateString();
                //生成文件夹
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                File.AppendAllText(directory + "\\" + timeN.ToString("yyyyMMddHH") + ".log", "************************" +
                    timeN.ToString("yyyy-MM-dd HH:mm:ss") + "***************************\r\n" + message + "\r\n");
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region datagrid添加行号
        private void inputDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,
                inputDataGridView.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), inputDataGridView.RowHeadersDefaultCellStyle.Font,
                rectangle, inputDataGridView.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
        }
        #endregion

        #region 打开查询窗口
        private Form selectForm;
        private void btnOpenQuery_Click(object sender, EventArgs e)
        {
            try
            {
                //窗口只打开一个
                if (selectForm == null || selectForm.IsDisposed)
                {
                    selectForm = new SelectForm();
                    selectForm.StartPosition = FormStartPosition.CenterScreen;
                    //selectForm.MdiParent = this;
                    selectForm.Show();
                }
                else
                {
                    selectForm.Activate();
                    selectForm.WindowState = FormWindowState.Normal;
                }
            }
            catch (Exception ex)
            {
                PrintLog(ex.ToString());
            }
        }
        #endregion

        #region 清空电池表单
        private void button3_Click(object sender, EventArgs e)
        {
            inputDataGridView.Rows.Clear();

        }
        #endregion

        #region 获取小车流水号
        //private RepeatForm reFrom;
        private void button4_Click(object sender, EventArgs e)
        {
            OpenThread("readCarNo");
        }
        #endregion


        private void btnKepServerConfig_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text.ToUpper().Equals("ZHHKKEPSERVER"))
            {
                frmOPCServerMark objfrmOPCSM = new MesDock.frmOPCServerMark();
                objfrmOPCSM.ShowDialog();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DisplayStatus();
            DataTable objTempDt = new DataTable();
            objTempDt = objIEqAlarm_BLL.getData("select tn.工位,Convert(decimal(18,2),tn.温度SV) as 温度SV,Convert(decimal(18,2),tn.温度测量值PV1) as 温度测量值PV1,Convert(decimal(18,2),tn.温度测量值PV2) as 温度测量值PV2,tn.真空度高限SV,tn.真空度低限SV,tn.真空度PV,tn.采集时间, tn.小车流水号" +
                                                     " from HK_EqTechnologyParameterInfo tn left join dbo.HK_EqStationCode tc on tn.工位 = tc.工位 " +
                                                     " where tn.采集时间 in(select MAX(t1.采集时间) from HK_EqTechnologyParameterInfo t1 group by t1.工位) order by tc.Item asc");

            ProcessDataGridView.DataSource = objTempDt.DefaultView;

        }

        private void btnTestPLC_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPlcAddress.Text))
            {
                txtPLCResult.Text = "";
                try
                {
                    txtPLCResult.Text = opc.ReadData(ChanneOtherDevice + txtPlcAddress.Text).ToString(); 
                }
                catch (Exception ex)
                {
                    var ResultData = opc.ReadData(ChanneOtherDevice + txtPlcAddress.Text);
                    int AscciiData = Convert.ToInt32(Convert.ToInt32(ResultData) % 256);
                    txtPLCResult.Text += ASCIIConvertString.Chr(AscciiData);
                    AscciiData = Convert.ToInt32(Convert.ToInt32(ResultData) / 256);
                    tbMessage.Text += ASCIIConvertString.Chr(AscciiData);
                }
            }

        }

        private void cboStation_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPLCResult.Text = "";
            try
            {

                string tempAddress = cboStation.Text.Split('_')[1];
                tempAddress = tempAddress.Substring(0, tempAddress.Length - 1);
                for (int i = 0; i < 10; i++)
                {
                    string plcAddress = null;
                    plcAddress = tempAddress + i.ToString();
                    var ResultData = opc.ReadData(ChanneOtherDevice + plcAddress);
                    int AscciiData = Convert.ToInt32(Convert.ToInt32(ResultData) % 256);
                    txtPLCResult.Text += ASCIIConvertString.Chr(AscciiData);
                    AscciiData = Convert.ToInt32(Convert.ToInt32(ResultData) / 256);
                    txtPLCResult.Text += ASCIIConvertString.Chr(AscciiData);
                }
            }
            catch (Exception ex)
            {
                tbMessage.Text = ex.Message.ToString();
            }
        }

        private void tsmRegister_Click(object sender, EventArgs e)
        {

        }
    }
}
